using Digitalmes.Application.Sys;
using Digitalmes.Common.Jwt;
using Digitalmes.Common.Jwt.Model;

namespace Digitalmes.Application.Operator;

/// <summary>
/// 操作人服务
/// </summary>
[ApiExplorerSettings(GroupName = "v1")]
public sealed class OperatorService : IDynamicWebApiService
{
    private readonly SysAdminService _adminService;
    private readonly SysOrganizeService _organizeService;
    private readonly SysLogService _logService;
    private readonly SugarRepository<SysOrganize> _thisRepository;

    public OperatorService(SysAdminService adminService, 
        SysOrganizeService organizeService, 
        SysLogService logService, 
        SugarRepository<SysOrganize> thisRepository)
    {
        _adminService = adminService;
        _organizeService = organizeService;
        _logService = logService;
        _thisRepository = thisRepository;
    }

    /// <summary>
    /// 用户登录入口
    /// </summary>
    /// <param name="loginParam"></param>
    /// <returns></returns>
    [AllowAnonymous]
    public async Task<LoginTokenDto> LoginAsync(LoginParam loginParam)
    {
        var loginRes = await _adminService.LoginAsync(loginParam);
        var token = JwtAuthHandler.IssueJwt(new JwtToken()
        { 
            Id = loginRes.Id, 
            FullName = loginRes.FullName, 
            Role = "Admin", 
            RoleArray = loginRes.RoleGroup.Count > 0 ? string.Join(",", loginRes.RoleGroup) : "0", 
            TenantId = loginRes.TenantId, 
            Time = DateTime.Now,
        });

        // 登录日志收集
        await _logService.AddAsync(new SysLogDto()
        {
            Level = LogEnum.Info,
            LogType = LogTypeEnum.Login,
            Module = "Login",
            Method = "Login",
            OperateUser = loginRes.FullName,
            Parameters = JsonSerializer.Serialize(loginParam),
            IP = HttpUtils.GetIp(),
            Address = "/api/login",
            Browser = HttpUtils.GetBrowser(),
        });

        return new LoginTokenDto()
        {
            accessToken = token,
            userInfo = new OperatorUser()
            {
                Id = loginRes.Id,
                TenantId = loginRes.TenantId,
                Username = loginRes.FullName,
                Avatar = loginRes.Avatar
            }
        };
    }

    /// <summary>
    /// 工作台用户信息
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<OperatorWorkDto> UserWord()
    {
        var token = AppUtils.Token;
        if (token.Id == 0)
        {
            return new OperatorWorkDto();
        }

        var model = await _adminService.GetAsync(token.Id);
        var organize = await _organizeService.GetAsync(model.OrganizeId);
        var roleList = await _thisRepository.Context.Queryable<SysRole>()
            .Where(m => model.RoleGroup.Contains(m.Id)).ToListAsync();
        var postList = await _thisRepository.Context.Queryable<SysPost>()
            .Where(m => model.PostGroup.Contains(m.Id)).ToListAsync();
        var messageCount = await _thisRepository.Context.Queryable<SysMessage>().CountAsync(m => true);
        var agencyCount = await _thisRepository.Context.Queryable<SysMessage>().CountAsync(m => !m.IsRead);

        return new OperatorWorkDto()
        {
            Account = model.LoginAccount,
            FullName = model.FullName,
            Sex = model.Sex,
            HeadPic = model.Avatar,
            Organize = organize.Name,
            Summary = model.Summary,
            Role = roleList.Select(m => m.Name).ToList(),
            Post = postList.Select(m => m.Name).ToList(),
            LastTime = model.UpLoginTime,
            LoginSum = model.LoginCount,
            MessageSum = messageCount,
            AgencySum = agencyCount
        };
    }

    /// <summary>
    /// 退出
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public ApiResult<int> Logout()
    {
        return JResult.Success();
    }
}
